package orm

import (
	"animal/octopus/common"
	"animal/octopus/model"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func CreateTopoRule(db *gorm.DB, param common.CreateTopoRuleParam) (uint, error) {
	rule := model.TopoRule{
		TopoViewID:  param.TopoViewID,
		Desc:        param.Desc,
		Regex:       param.Regex,
		Replacement: param.Replacement,
	}
	if err := common.DB(db).Create(&rule).Error; err != nil {
		log.Error("create topo rule failed")
		return 0, err
	}

	return rule.ID, nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func GetTopoRuleList(db *gorm.DB, topoViewID uint) ([]common.TopoRuleInfo, error) {
	var topoRuleInfos []common.TopoRuleInfo

	var topoRules []model.TopoRule
	result := db.Find(&topoRules, "topo_view_id = ?", topoViewID)
	if result.Error != nil {
		log.Error("find topo view failed")
		return nil, result.Error
	}

	for _, rule := range topoRules {
		topoRuleInfos = append(topoRuleInfos, common.TopoRuleInfo{
			ID:          rule.ID,
			TopoViewID:  rule.TopoViewID,
			Desc:        rule.Desc,
			Regex:       rule.Regex,
			Replacement: rule.Replacement,
		})
	}

	return topoRuleInfos, nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func DeleteTopoRule(db *gorm.DB, param common.DeleteTopoRuleParam) error {
	if err := common.DB(db).Where("id = ?", param.ID).Unscoped().
		Delete(&model.TopoRule{}).Error; err != nil {
		log.WithFields(log.Fields{
			"view":  param.ID,
			"error": err,
		}).Error("delete topo rule failed")
		return common.NewErrCode(common.ErrDatabaseError)
	}
	return nil
}
